package com.leps.nq.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leps.nq.bu.entity.BuWell;
import com.leps.nq.bu.service.IBuWellService;
import com.leps.nq.common.util.JSONUtils;
import com.leps.nq.common.vo.QRCodeBean;
import com.leps.nq.config.NqConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@Api(tags = "二维码下载接口")
@RestController
public class QRCodeController {
    @Autowired
    IBuWellService wellService;
    @Autowired
    ObjectMapper objectMapper;

    @ApiOperation("批量下载二维码")
    @GetMapping("/qrcode/down")
    public ResponseEntity<InputStreamResource> down(HttpServletResponse response) throws IOException {
        // get all wells
        List<BuWell> wells = wellService.list();
        // generate qrcode files
        String qrcodeDir = NqConfig.getQrcodeDir();
        wells.forEach(well -> {
            QRCodeBean qrCodeBean = BeanUtil.toBean(well, QRCodeBean.class);
            String json = JSONUtils.toJson(qrCodeBean);
            String filename = qrcodeDir + File.separator + well.getWellName() + ".jpg";
            QrCodeUtil.generate(json, 300, 300, FileUtil.file(filename));
        });
        // zip qrcode files
        File zipFile = ZipUtil.zip(qrcodeDir);

        return ResponseEntity
                .ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-Disposition", "attachment;filename=" + URLEncoder.encode("井二维码", "UTF-8") + ".zip")
                .body(new InputStreamResource(new FileInputStream(zipFile)));
    }
}
